﻿// Write your JavaScript code.

Date.prototype.now = function () {
    return '[' + this.getHours() + ':' + this.getMinutes() + ':' + this.getSeconds() + ']';
};

//处理进度框对象
var progressInfo = new Progress();
//端口控制对象
var portControl = new PortControl();
//矩阵控制对象
var matrixControl = new MatrixControl(progressInfo, portControl);
//Session监听对象
var sessionWatcher = new SessionWatcher();
sessionWatcher.SessionTimeoutHandler = logout;
//localStorage管理对象
var localStorageManager = new LocalStorageManager(localStorage);
//客户端管理对象
var clientManager = new ClientManager();

/**
 * 页面加载
 */
function page_Load() {
    localStorageManager.pageLoad();
    progressInfo.init();

    if (localStorageManager.isLogin()) {
        $('#login').hide();
        $('#logout').show();

        initNotifier();
        sessionWatcher.watch();
    } else {
        $('#login').show();
        $('#logout').hide();
    }
}

/**
 * 页面退出
 */
function page_Unload() {
    localStorageManager.pageUnload();

    sessionWatcher.stop();
}

/**
 * 创建websocket通信对象
 */
function initNotifier() {
    var clientIP = localStorageManager.getClientIP();
    var notifier = new Notifier('ws://localhost:4649/matrix', clientIP, localStorageManager);
    notifier.onmessage(function (messageEvent) {
        var data = messageEvent.data;
        if (!data) {
            return;
        }

        //矩阵状态变更通知
        if (data.indexOf('MSC') >= 0) {
            //矩阵列表页面
            var matrixView = $('#matrixView');
            if (matrixView.length > 0) {
                notifyMatrixStatusChanged(data, matrixView);
                return;
            }

            //矩阵详细页面
            var matrixDetail = $('#matrixDetail');
            if (matrixDetail.length > 0) {
                notifyMatrixStatusChanged(data, matrixDetail, true);
            }
        } else if (data.indexOf('PSC') >= 0) { //矩阵交叉点状态变更通知
            var matrixDetail = $('#matrixDetail');
            //矩阵详细页面接收交叉点状态变更通知
            if (matrixDetail.length > 0) {
                notifyCptSwitchChanged(data, matrixDetail);
            }
        } else if (data.indexOf('LSC') >= 0) { //矩阵端口锁定状态变更通知
            var matrixDetail = $('#matrixDetail');
            //矩阵详细页面接收端口锁定状态变更通知
            if (matrixDetail.length > 0) {
                notifyPortLockStatusChanged(data, matrixDetail);
            }
        } else if (data.indexOf('CIC') >= 0) { //客户端状态变更通知
            localStorageManager.updateLastAccessTime(new Date());
            var clientView = $('#clientView');
            //客户端列表页面接收客户端在线状态变更通知
            if (clientView.length > 0) {
                clientManager.notifyClientStatusChanged(data, clientView);
            }
        }
    });
    notifier.init();
}

/**
 * 获取当前时间字符串
 */
function getNowString() {
    var now = new Date();
    return '[' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds() + ']';
}

/**
 * 通知页面更新矩阵状态变更
 * @param {any} data
 * @param {any} container
 */
function notifyMatrixStatusChanged(data, matrixContainer, isDetailPage) {
    console.log(getNowString() + ' :' + data);

    //data格式：MSC-matrixId-matrixStatus
    var infoes = data.split('-');
    if (infoes && infoes.length == 3) {
        var matrixId = infoes[1];
        var matrixStatus = infoes[2];

        //非当前矩阵的详细页面不通知
        if (isDetailPage && matrixContainer.find('#matrix_' + matrixId).length == 0) {
            return;
        }

        var matrix = isDetailPage ? matrixContainer : matrixContainer.children('#matrix_' + matrixId);
        if (matrix.length > 0) {
            var iconStatus = matrix.find('#iconStatus');
            var circleStatus = matrix.find('#circleStatus');
            if (matrixStatus == 'True') {
                iconStatus.removeClass('matrixIcon-offline').addClass('matrixIcon-online');
                circleStatus.removeClass('matrixCircle-offline').addClass('matrixCircle-online');
                circleStatus.attr('title', '在线');
            } else {
                iconStatus.removeClass('matrixIcon-online').addClass('matrixIcon-offline');
                circleStatus.removeClass('matrixCircle-online').addClass('matrixCircle-offline');
                circleStatus.attr('title', '离线');
            }
        }
    }
}

/**
 * 通知页面更新端口切换变更
 * @param {any} data
 * @param {any} matrixContainer
 */
function notifyCptSwitchChanged(data, matrixContainer) {
    console.log(getNowString() + ' :' + data);

    //data格式：PSC-matrixId-srcPortId-destPortId
    var infoes = data.split('-');
    if (infoes && infoes.length == 4) {
        var matrixId = infoes[1];
        var srcPortId = infoes[2];
        var destPortId = infoes[3];

        //非当前矩阵的页面不通知
        if (matrixContainer.find('#matrix_' + matrixId).length == 0) {
            return;
        }

        var destPort = matrixContainer.find('#destPorts').children('#port' + destPortId);
        if (destPort.length > 0) {
            //将切换后的新源端口更新至目的端口属性中
            portControl.setLinkToSrcPort(destPort, srcPortId);
            //目的端口处于选中状态时，更新链接源端口状态
            if (portControl.portIsSelecting(destPort)) {
                //取消旧的连接源端口样式
                portControl.cancelLinkToSrcPortSelectStatus();
                //设置新源端口样式
                portControl.selectLinkToSrcPort(srcPortId);
            }
        }
    }
}

/**
 * 通知页面更新端口锁定状态变更
 * @param {any} data
 * @param {any} matrixContainer
 */
function notifyPortLockStatusChanged(data, matrixContainer) {
    console.log(getNowString() + ' :' + data);

    //data格式：MSC-matrixId-destPortId-portStatus
    var infoes = data.split('-');
    if (infoes && infoes.length == 4) {
        var matrixId = infoes[1];
        var destPortId = infoes[2];
        var portStatus = infoes[3];

        //非当前矩阵的页面不通知
        if (matrixContainer.find('#matrix_' + matrixId).length == 0) {
            return;
        }

        var destPort = matrixContainer.find('#destPorts').children('#port' + destPortId);
        if (destPort.length > 0) {
            if (portStatus == 'Locking') {
                destPort.addClass('matrixPort-locking');
            } else {
                destPort.removeClass('matrixPort-locking').addClass('matrixPort');
            }
        }
    }
}

/**
 * 登录
 */
function doLogin() {
    var userId = $('#userId').val();
    var pwd = $('#pwd').val();
    $.ajax({
        url: '/Login/Login',
        method: 'post',
        data: { 'UserId': userId, 'Pwd': pwd },
        datatype: 'json'
    }).success(function (result) {
        if (result && result.item1) {
            localStorageManager.add('isLogin', result.item1);
            localStorageManager.add('clientIP', result.item2);
            localStorageManager.updateLastAccessTime(new Date());
            location.href = '/Matrix/MatrixView';
        } else {
            alert(result.item2);
        }
    }).fail(function (xhr, error) {
        alert(error);
    });
}

/**
 * 登出
 */
function logout() {
    $.ajax({
        url: '/Login/DoLogout',
        method: 'post',
        data: { 'forceExit': false },
        datatype: 'json'
    }).success(function (data) {
        if (data == true) {
            localStorageManager.clearLoginInfo();
            location.href = '/Matrix/Login';
        } else {
            alert(data.item2);
        }
    }).fail(function (xhr, error) {
        console.log(error);
    });
}

/**
 * 矩阵端口切换事件
 * @param {any} matrixId
 */
function btnTake_Click(matrixId) {
    matrixControl.patchTake(matrixId);
}

/**
 * 矩阵端口锁定/解锁事件
 * @param {any} matrixId
 * @param {any} doLock
 */
function btnLock_Click(matrixId, doLock) {
    matrixControl.patchLock(matrixId, doLock);
}

/**
 * 矩阵端口选中/反选处理
 * @param {any} portItem
 */
function port_Click(portItem) {
    var portElement = $(portItem);
    //依据父元素ID判断是源口还是出口
    var parentId = portElement.parent().attr('id');
    if (parentId == 'srcPorts') {
        //源端口选中处理
        portControl.selectSrcPort(portElement);
    } else {
        //出端口选中处理
        portControl.selectDestPort(portElement);
    }

    //设定按钮(切换、锁定)可用性
    setButtonEnable();
}

/**
 * “多选”CheckedChanged事件
 */
function mutilSelect_CheckedChanged() {
    var checked = $('#canMutilSelect').is(':checked');
    if (!checked) {
        //取消端口选中状态
        portControl.cancelPortSelectStatus();
        //设定按钮(切换、锁定)可用性
        setButtonEnable();
    }
}

/**
 * 设定按钮(切换、锁定)可用性
 */
function setButtonEnable() {
    //切换按钮
    setTakeButtonStyle()
    //锁定按钮
    setLockButtonStyle()
}

/**
 * 设定切换按钮样式
 */
function setTakeButtonStyle() {
    var destPortSelectedCount = portControl.getSelectedDestPorts(true);
    var srcPortSelectedCount = portControl.getSelectedSrcPorts(true);
    //切换按钮
    $('#btnTake').toggleClass('disabled', !(destPortSelectedCount > 0 && srcPortSelectedCount == 1));
}

/**
 * 设定锁定按钮样式
 */
function setLockButtonStyle() {
    var selectingDestPort = portControl.getSelectedDestPorts();
    //设定锁定按钮状态
    $('#btnLock').toggleClass('disabled', selectingDestPort.length == 0);
    //设定锁定按钮文本
    $('#btnLock').val(selectingDestPort.hasClass('matrixPort-locking') ? "解除锁定" : "锁定端口");
}